﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows;
using System.Windows.Input;
using MagicKey;
using MagicKey.Components.UserManager;
using MagicKey.Factory;
using MagicKey.Interfaces;
using Microsoft.Win32;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
using MessageBox = System.Windows.MessageBox;


namespace Emergency
{
    /// <summary>
    /// Interaktionslogik für Notar.xaml
    /// </summary>
    public partial class Notar : Window
    {
        private MagicKeyFactory _factory = MagicKeyFactory.GetInstance();
        private IFileAccess fileAccess;
        private IMagicKey iMagicKey;
        private IUserManager userManager;
        private string filename;
        private string privateKey;
        private IDatabase database;
        public Notar()
        {
            InitializeComponent();
            iMagicKey = _factory.GetMagicKeyInterface();
            fileAccess = iMagicKey.GetFileAccess();
            database = iMagicKey.GetDatabase("dba2");

            userManager = iMagicKey.GetUserManager();
        }


        #region Methods
        private void OpenFile(object sender, RoutedEventArgs e)
        {
            filename = string.Empty;

            // Configure open file dialog box
            String input = string.Empty;

            OpenFileDialog dialog = new OpenFileDialog();

            // Show open file dialog box
            bool? result = dialog.ShowDialog();
            dialog.InitialDirectory = "C:";
            dialog.Title = "Select a text file";
            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                filename = dialog.FileName;
                this.KeyTextBox.Text = filename;
            }
            

        }

        private bool WriteFile(string outpath, string lines)
        {
            try
            {
                StreamWriter mysavefile = new StreamWriter(outpath);
                mysavefile.Write(lines);
                mysavefile.Close();
                return true;
            }
            catch (Exception ex)
            {
                // System.Windows.MessageBox.Show("WriteFile exception.\r\n" + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return false;
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            var accessManager = iMagicKey.GetAccessManager();
            string superUserName = "Controlchef";
            User superUser = new User()
            {
                Name = superUserName,
                Salt = database.LoadParameterUser("salt", superUserName),
            };

            if (!filename.Equals(string.Empty) && File.Exists(filename))
            {
                privateKey = GetPrivateKey(filename);
                

                // load all dba2 entries
                string allEntries = this.database.LoadAllEntries();

                // Decrypt all dba2 entries
string allEntriesDecrypted = string.Empty;
                string startToIgnore = "#";
                
                string content = string.Empty;
                string newContent = string.Empty;
                string[] delimiterstring = {","};
                string[] cols;
                int index2StartDelimit;
                StreamReader myfile = new StreamReader(filename, Encoding.UTF8);

                    while (!myfile.EndOfStream)
                    {
                        content = myfile.ReadLine();
                        if (!content.StartsWith(startToIgnore) && !content.Trim().Equals(string.Empty))
                        {
                            cols = content.Split(delimiterstring, StringSplitOptions.None);
                            //decrypt each entry
                            index2StartDelimit = 0;
                            newContent = string.Empty;
                            foreach (string col in cols)
                            {
                                if (index2StartDelimit > 0)
                                {
                                    newContent += ",";
                                }
                                //newContent += accessManager.DecryptStringAsym(col, privateKey);
                            }
                            // end of the line
                            newContent += "\r\n";
                        }
                        else
                        {
                            newContent = content;
                        }

                        allEntriesDecrypted += newContent;
                    }

                    myfile.Close();
               
                
                // Save all decrypted dba2 entries
                WriteFile(filename, allEntries);
                //filename = accessManager.DecryptFileSym(superUser,);


                //this.schlüsseltextbox.Text
            }
            else
            {
                MessageBox.Show("Please a file to be loaded!", "Notar error",
                                      MessageBoxButton.OK, MessageBoxImage.Error);
            }


        }

        private string GetPrivateKey(string path)
        {
            // Read private key from file
            StreamReader streamReader = new StreamReader(this.filename, Encoding.UTF8);
            string key = streamReader.ReadToEnd();
            streamReader.Close();
            return key;
        }

        #endregion Methods

    }
}



